import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import MenuRegister from '@/router/menuRegister'

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      path: route.url,
      component: route.parentId === '' ? Layout : MenuRegister[route.comName],
      alwaysShow: route.parentId === '',
      meta: { title: route.name, icon: route.icon, id: route.id, affix: route.affix},
      name: route.comName,
      hidden: route.hidden === 'Y'
    }

    if (route.children != null && route.children !== undefined && route.children.length > 0) {
      tmp.children = filterAsyncRoutes(route.children, roles)
    }
    res.push(tmp)
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const MenuInfo = JSON.parse(window.sessionStorage.getItem('AuthInfo')).menuInfo
      const accessedRoutes = filterAsyncRoutes(MenuInfo, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
